package server;

import gwtupload.server.UploadAction;
import gwtupload.server.exceptions.UploadActionException;

import java.util.Date;
import java.util.List;

import javax.ejb.EJB;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;

import phasebook.client.DirtyRegionManager;
import phasebook.client.DirtyRegionManager.Region;
import phasebook.client.RemotePhasebookService;
import phasebook.client.msgs.PhotoInfo;

public class UploadServlet extends UploadAction {
	private static final long serialVersionUID = -5295312823436715168L;

	@EJB
	RemotePhasebookService service;
	
	private RemotePhasebookService getService() {
		if (service!=null) // running in production with EJB injection
			return service;
		else //for web-development use this dummy service
			return DevPhasebookService.getInstance();
	}
	
	@EJB
	DirtyRegionManager regionManager;
	
	private DirtyRegionManager getRegionManager() {
		if (regionManager!=null) // running in production with EJB injection
			return regionManager;
		else //for web-development use this dummy service
			return DevPhasebookService.getInstance();
	}

	@Override
	public String executeAction(HttpServletRequest request,List<FileItem> sessionFiles) throws UploadActionException {
		String msg = "";
		try {
			for (FileItem item : sessionFiles) {

				PhotoInfo photo = new PhotoInfo();
				photo.setUrl(item.getName());
				photo.setUploadTimestamp(new Date());
				long userId = (Long) super.perThreadRequest.get().getSession().getAttribute("userId");
				getService().addPhoto(userId, photo, item.get());

				msg += "Uploaded: " + item.getName() + "\n";
				
				getRegionManager().publishDirtyRegions(userId, Region.Album);
			}
		} catch (Exception e) {
			throw new UploadActionException(e);
		}
		
		removeSessionFileItems(request);

		return msg;
	}
}
